import React, { useRef, useState, useEffect, useContext } from 'react';
import { Layout, Table, Button, Spin, message, Input } from 'antd';
import { ReloadOutlined, EditOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons';
import { BsFileEarmarkCode } from 'react-icons/bs';
import axios from 'axios';
import { API_BASE_URL } from '../config';
import { TabsContext } from '../contexts/TabsContext';

// 自定义样式
const customStyles = `
  .product-bop-container {
    height: 100%;
    background-color: #fff;
    border-radius: 4px;
    overflow: hidden;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  }
  
  .data-table {
    width: 100%;
  }
  
  .table-row-normal-height td {
    padding: 16px 8px;
  }
  
  .table-row-compact-height td {
    padding: 8px;
  }
  
  .compact-table .ant-table-thead > tr > th {
    padding: 8px;
  }
  
  .pagination-container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 16px;
    border-top: 1px solid #e8e8e8;
    background: #fff;
  }
  
  .table-header-actions {
    padding: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
  
  .action-buttons {
    display: flex;
    gap: 8px;
  }
  
  .horizontal-scroll-container {
    overflow-x: auto !important;
    overflow-y: hidden !important;
    display: block !important;
  }
  
  .ant-table-wrapper, .ant-table, .ant-table-container {
    min-width: 1200px !important;
  }
  
  /* 美化表格边框和表头 */
  .ant-table {
    border: 1px solid #e8e8e8 !important;
  }
  
  .ant-table-thead > tr > th {
    background-color: #f7f7f7 !important;
    font-weight: bold !important;
    border-bottom: 1px solid #e8e8e8 !important;
  }
  
  @media (max-width: 576px) {
    .product-bop-container {
      margin: 0;
      border-radius: 0;
    }
    
    .horizontal-scroll-container .ant-table-wrapper, 
    .horizontal-scroll-container .ant-table, 
    .horizontal-scroll-container .ant-table-container {
      min-width: 800px !important;
    }
    
    .ant-table-cell {
      padding: 4px !important;
      font-size: 12px !important;
    }
  }
  
  .bop-detail-item {
    display: grid;
    grid-template-columns: 120px 1fr;
    margin-bottom: 16px;
    align-items: center;
  }

  .bop-detail-label {
    color: #666;
    text-align: right;
    padding-right: 16px;
    font-weight: 500;
  }

  .bop-detail-value {
    color: #333;
  }

  .bop-detail-actions {
    display: flex;
    justify-content: flex-end;
    margin: 16px;
  }

  /* BOP详情页样式 */
  .bop-detail-container {
    height: 100%;
    display: flex;
    flex-direction: column;
    background: #f0f2f5;
    overflow: auto;
  }
  
  .bop-detail-header {
    padding: 0;
    background: #fff;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    z-index: 1;
  }
  
  .bop-detail-tabs {
    display: flex;
    align-items: center;
    padding: 0 16px;
    border-bottom: 1px solid #e8e8e8;
  }
  
  .bop-detail-tab {
    padding: 16px 0;
    margin-right: 24px;
    cursor: pointer;
    position: relative;
    font-size: 14px;
  }
  
  .bop-detail-tab.active {
    color: #1766a3;
    font-weight: bold;
  }
  
  .bop-detail-tab.active::after {
    content: '';
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    height: 2px;
    background: #1766a3;
  }
  
  .bop-detail-content {
    padding: 24px;
    background: #fff;
    margin: 16px;
    flex: 1;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    overflow: auto;
  }
  
  /* 响应式样式 */
  @media (max-width: 576px) {
    .bop-detail-content {
      padding: 16px;
      margin: 8px;
    }
    
    .bop-detail-label {
      flex: 0 0 100px;
    }
    
    .bop-detail-tab {
      padding: 12px 0;
      margin-right: 16px;
    }
  }
`;

const { Content } = Layout;

const ProductBOP = () => {
  // 使用TabsContext上下文
  const { addTab } = useContext(TabsContext);

  // 表格容器引用，用于横向滚动
  const tableContainerRef = useRef(null);
  
  // 状态管理
  const [loading, setLoading] = useState(false);
  const [bopList, setBopList] = useState([]);
  const [productInfoMap, setProductInfoMap] = useState({});
  const [isMobile, setIsMobile] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  
  // 分页相关状态
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const inputRef = useRef(null);

  // 检测是否为移动设备
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth <= 576);
    };
    
    checkIsMobile();
    window.addEventListener('resize', checkIsMobile);
    
    return () => {
      window.removeEventListener('resize', checkIsMobile);
    };
  }, []);

  // 获取产品BOP列表
  const fetchProductBOPList = async (page = 1, pageSize = 10) => {
    setLoading(true);
    try {
      const response = await axios.get(`${API_BASE_URL}/api/product_bop`, {
        params: {
          page,
          size: pageSize
        }
      });
      
      if (response.data && response.data.code === 200) {
        const items = response.data.data.items || [];
        
        // 处理返回的数据，确保所有必要字段都存在
        const processedItems = items.map(item => ({
          ...item,
          key: item.id,
          name: item.name || '未命名',
          code: item.code || '-',
          current_version: item.current_version || '-',
          create_time: item.create_time || null
        }));
        
        console.log('产品BOP列表数据:', processedItems);
        setBopList(processedItems);
        
        // 更新分页状态
        setPagination({
          ...pagination,
          current: page,
          pageSize: pageSize,
          total: response.data.data.total || 0
        });
        setCurrentPage(page);
        
        // 收集所有的product_id，后续获取产品详情
        const productIds = processedItems.map(item => item.product_id).filter(id => id);
        if (productIds.length > 0) {
          fetchProductInfos(productIds);
        }
      } else {
        message.error('获取产品BOP列表失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取产品BOP列表错误:', error);
      message.error('获取产品BOP列表失败: ' + (error.message || '网络错误'));
    } finally {
      setLoading(false);
    }
  };

  // 获取产品详细信息
  const fetchProductInfos = async (productIds) => {
    try {
      // 创建一个临时的产品信息映射
      const tempProductInfoMap = { ...productInfoMap };
      
      // 并行获取每个产品的详细信息
      const promises = productIds.map(async (id) => {
        if (tempProductInfoMap[id]) return; // 如果已经有了，就不再获取
        
        try {
          const response = await axios.get(`${API_BASE_URL}/api/product_info/${id}`);
          if (response.data && response.data.code === 200) {
            tempProductInfoMap[id] = response.data.data;
          }
        } catch (error) {
          console.error(`获取产品 ${id} 详情失败:`, error);
        }
      });
      
      // 等待所有请求完成
      await Promise.all(promises);
      
      // 更新产品信息映射
      setProductInfoMap(tempProductInfoMap);
    } catch (error) {
      console.error('获取产品信息错误:', error);
    }
  };

  // 处理页码变化
  const handlePageChange = (page) => {
    setCurrentPage(page);
    fetchProductBOPList(page, pageSize);
  };

  // 处理页码输入
  const handlePageInputChange = (e) => {
    const value = parseInt(e.target.value, 10);
    if (!isNaN(value)) {
      setCurrentPage(value);
    }
  };

  // 处理页码输入框按键事件
  const handlePageInputKeyPress = (e) => {
    if (e.key === 'Enter') {
      const value = parseInt(e.target.value, 10);
      if (!isNaN(value) && value > 0 && value <= Math.ceil(pagination.total / pageSize)) {
        fetchProductBOPList(value, pageSize);
      }
    }
  };

  // 前一页
  const goPrevPage = () => {
    if (currentPage > 1) {
      const prevPage = currentPage - 1;
      setCurrentPage(prevPage);
      fetchProductBOPList(prevPage, pageSize);
    }
  };

  // 后一页
  const goNextPage = () => {
    if (currentPage < Math.ceil(pagination.total / pageSize)) {
      const nextPage = currentPage + 1;
      setCurrentPage(nextPage);
      fetchProductBOPList(nextPage, pageSize);
    }
  };

  // 打开BOP详情页签
  const openBOPDetail = (record) => {
    // 打开一个新的页签，用于展示BOP详情
    const tabKey = `bopDetail-${record.id}`;
    const tabTitle = `${record.code}`;
    addTab(tabKey, tabTitle, 'BOPDetail', { bopId: record.id, code: record.code });
  };

  // 打开产品详情
  const openProductDetail = (productId) => {
    if (!productId) return;
    
    // 获取产品信息
    const productInfo = productInfoMap[productId] || {};
    
    // 打开一个新的页签，用于展示产品详情
    const tabKey = `productDetail-${productId}`;
    const tabTitle = `${productInfo.code || '产品'}`;
    addTab(tabKey, tabTitle, 'ProductDetail', { productId });
  };

  // 列定义
  const getTableColumns = () => {
    const baseColumns = [
      {
        title: 'BOP名称',
        dataIndex: 'name',
        key: 'name',
        align: 'left',
        ellipsis: true,
        render: (text, record) => (
          <span 
            style={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }}
            onClick={() => openBOPDetail(record)}
          >
            <BsFileEarmarkCode 
              style={{ 
                fontSize: isMobile ? '12px' : '16px', 
                marginRight: isMobile ? '4px' : '8px',
                color: '#1766a3'
              }} 
            />
            <span>{text}</span>
          </span>
        )
      },
      {
        title: '编码',
        dataIndex: 'code',
        key: 'code',
        align: 'center',
        ellipsis: true,
        render: (text, record) => (
          <span 
            style={{ display: 'block', width: '100%', textAlign: 'center', cursor: 'pointer' }}
            onClick={() => openBOPDetail(record)}
          >
            {text || '-'}
          </span>
        )
      },
      {
        title: '版本',
        dataIndex: 'current_version',
        key: 'current_version',
        align: 'center',
        ellipsis: true,
        render: (text, record) => (
          <span 
            style={{ display: 'block', width: '100%', textAlign: 'center', cursor: 'pointer' }}
            onClick={() => openBOPDetail(record)}
          >
            {text || '-'}
          </span>
        )
      }
    ];
    
    // 移动端显示核心列
    if (isMobile) {
      return baseColumns;
    }
    
    // 桌面端显示完整列
    return [
      ...baseColumns,
      {
        title: '产品名称',
        dataIndex: 'product_id',
        key: 'product_name',
        align: 'center',
        ellipsis: true,
        render: (productId) => {
          const productInfo = productInfoMap[productId] || {};
          return (
            <span 
              style={{ display: 'block', width: '100%', textAlign: 'center', cursor: 'pointer' }}
              onClick={() => openProductDetail(productId)}
            >
              {productInfo.name || '-'}
            </span>
          );
        }
      },
      {
        title: '产品编码',
        dataIndex: 'product_id',
        key: 'product_code',
        align: 'center',
        ellipsis: true,
        render: (productId) => {
          const productInfo = productInfoMap[productId] || {};
          return (
            <span 
              style={{ display: 'block', width: '100%', textAlign: 'center', cursor: 'pointer' }}
              onClick={() => openProductDetail(productId)}
            >
              {productInfo.code || '-'}
            </span>
          );
        }
      },
      {
        title: '产品类型',
        dataIndex: 'product_id',
        key: 'product_type',
        align: 'center',
        ellipsis: true,
        render: (productId) => {
          const productInfo = productInfoMap[productId] || {};
          return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{productInfo.product_type || '-'}</span>;
        }
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        key: 'create_time',
        align: 'center',
        ellipsis: true,
        render: (text) => {
          if (!text) return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>-</span>;
          try {
            const date = new Date(text);
            if (!isNaN(date.getTime())) {
              return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>
                {date.toLocaleString('zh-CN', {
                  year: 'numeric',
                  month: '2-digit',
                  day: '2-digit',
                  hour: '2-digit',
                  minute: '2-digit',
                  second: '2-digit',
                  hour12: false
                }).replace(/\//g, '-')}
              </span>;
            }
            return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{text}</span>;
          } catch (error) {
            console.error('日期格式化错误:', error);
            return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{text || '-'}</span>;
          }
        }
      }
    ];
  };

  // 根据数据行数确定行高
  const getRowClassName = () => {
    const dataLength = bopList.length;
    if (dataLength >= 10 || isMobile) {
      return "table-row-compact-height";
    }
    return "table-row-normal-height";
  };

  // 组件挂载时加载数据
  useEffect(() => {
    fetchProductBOPList();
  }, []);

  // 刷新数据
  const handleRefresh = () => {
    fetchProductBOPList(pagination.current, pagination.pageSize);
  };

  return (
    <Layout className={`product-bop-container ${isMobile ? 'mobile-layout' : ''}`}>
      <style dangerouslySetInnerHTML={{ __html: customStyles }} />
      <Content style={{ padding: '0', height: '100%' }}>
        <div style={{ 
          height: '100%',
          display: 'flex',
          flexDirection: 'column'
        }}>
          {/* 标题栏 */}
          <div className="table-header-actions">
            <div style={{ 
              fontWeight: 'bold', 
              fontSize: isMobile ? '14px' : '18px',
              display: 'flex',
              alignItems: 'center',
              color: '#1766a3'
            }}>
              <BsFileEarmarkCode style={{ marginRight: '8px' }} />
              <span>产品BOP列表</span>
            </div>
            <div className="action-buttons">
              <Button 
                icon={<ReloadOutlined />}
                onClick={handleRefresh}
                size={isMobile ? 'small' : 'middle'}
                title="刷新数据"
              >
                刷新
              </Button>
            </div>
          </div>
          
          {/* 表格容器 */}
          <div style={{ flex: 1, overflow: 'auto' }}>
            <div 
              ref={tableContainerRef}
              className="horizontal-scroll-container"
              data-rows-count={bopList.length > 10 ? "many" : "few"}
            >
              <Spin spinning={loading}>
                <Table
                  className={`data-table ${bopList.length >= 10 || isMobile ? 'compact-table' : ''}`}
                  dataSource={bopList}
                  columns={getTableColumns()}
                  pagination={false}
                  rowClassName={getRowClassName}
                  size={isMobile || bopList.length >= 10 ? 'small' : 'middle'}
                  bordered={true}
                  scroll={{ x: bopList.length > 0 ? (isMobile ? 800 : 'max-content') : undefined }}
                  tableLayout="auto"
                  locale={{ emptyText: '暂无数据' }}
                />
              </Spin>
            </div>
          </div>
          
          {/* 自定义分页 */}
          <div className="pagination-container">
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <span>共 {pagination.total} 条，{Math.ceil(pagination.total / pageSize)} 页</span>
            </div>
            
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Button 
                icon={<LeftOutlined />}
                onClick={goPrevPage}
                disabled={currentPage === 1}
                style={{ marginRight: '8px' }}
              />
              
              <Input
                ref={inputRef}
                style={{ width: '50px', textAlign: 'center', margin: '0 8px' }}
                value={currentPage}
                onChange={handlePageInputChange}
                onKeyPress={handlePageInputKeyPress}
              />
              
              <span style={{ margin: '0 8px' }}>/ {Math.ceil(pagination.total / pageSize)}</span>
              
              <Button 
                icon={<RightOutlined />}
                onClick={goNextPage}
                disabled={currentPage >= Math.ceil(pagination.total / pageSize)}
                style={{ marginLeft: '8px', marginRight: '8px' }}
              />
              
              <span style={{ marginLeft: '8px' }}>
                {pageSize} / 页
              </span>
            </div>
          </div>
        </div>
      </Content>
    </Layout>
  );
};

// 产品BOP详情组件
const BOPDetail = ({ bopId }) => {
  const { addTab } = useContext(TabsContext);

  const [loading, setLoading] = useState(false);
  const [bopDetail, setBopDetail] = useState(null);
  const [activeTab, setActiveTab] = useState('detail');
  const [isMobile, setIsMobile] = useState(false);
  
  // 资源列表状态
  const [resources, setResources] = useState([]);
  const [resourcesLoading, setResourcesLoading] = useState(false);
  const [resourcesPagination, setResourcesPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [resourcesCurrentPage, setResourcesCurrentPage] = useState(1);
  const [resourcesPageSize, setResourcesPageSize] = useState(10);
  const resourcesInputRef = useRef(null);
  
  // 物料列表状态
  const [materials, setMaterials] = useState([]);
  const [materialsLoading, setMaterialsLoading] = useState(false);
  const [materialsPagination, setMaterialsPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [materialsCurrentPage, setMaterialsCurrentPage] = useState(1);
  const [materialsPageSize, setMaterialsPageSize] = useState(10);
  const materialsInputRef = useRef(null);
  // 产品详情映射
  const [productInfoMap, setProductInfoMap] = useState({});

  // 检测是否为移动设备
  useEffect(() => {
    const checkIsMobile = () => {
      setIsMobile(window.innerWidth <= 576);
    };
    
    checkIsMobile();
    window.addEventListener('resize', checkIsMobile);
    
    return () => {
      window.removeEventListener('resize', checkIsMobile);
    };
  }, []);

  // 获取产品BOP详情
  useEffect(() => {
    const fetchBOPDetail = async () => {
      if (!bopId) return;
      
      setLoading(true);
      try {
        const response = await axios.get(`${API_BASE_URL}/api/product_bop/${bopId}`);
        
        if (response.data && response.data.code === 200) {
          console.log('BOP详情数据:', response.data.data);
          setBopDetail(response.data.data);
        } else {
          message.error('获取BOP详情失败: ' + (response.data.message || '未知错误'));
        }
      } catch (error) {
        console.error('获取BOP详情错误:', error);
        message.error('获取BOP详情失败: ' + (error.message || '网络错误'));
      } finally {
        setLoading(false);
      }
    };

    fetchBOPDetail();
  }, [bopId]);

  // 获取资源列表
  const fetchResourceList = async (page = 1, pageSize = 10) => {
    if (!bopId) return;
    
    setResourcesLoading(true);
    try {
      // 使用接口文档中的 GET /api/product_bop_resource 接口
      const response = await axios.get(`${API_BASE_URL}/api/product_bop_resource`, {
        params: {
          product_bop_id: bopId,
          page,
          size: pageSize
        }
      });
      
      if (response.data && response.data.code === 200) {
        console.log('BOP资源列表数据:', response.data.data);
        const items = response.data.data.items || [];
        
        // 处理返回的数据
        const processedItems = items.map(item => ({
          ...item,
          key: item.id
        }));
        
        setResources(processedItems);
        setResourcesPagination({
          ...resourcesPagination,
          current: page,
          pageSize: pageSize,
          total: response.data.data.total || 0
        });
        setResourcesCurrentPage(page);
      } else {
        message.error('获取BOP资源列表失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取BOP资源列表错误:', error);
      message.error('获取BOP资源列表失败: ' + (error.message || '网络错误'));
    } finally {
      setResourcesLoading(false);
    }
  };
  
  // 获取物料列表
  const fetchMaterialList = async (page = 1, pageSize = 10) => {
    if (!bopId) return;
    
    setMaterialsLoading(true);
    try {
      // 使用接口文档中的 GET /api/product_bop_material 接口
      const response = await axios.get(`${API_BASE_URL}/api/product_bop_material`, {
        params: {
          product_bop_id: bopId,
          page,
          size: pageSize
        }
      });
      
      if (response.data && response.data.code === 200) {
        console.log('BOP物料列表数据:', response.data.data);
        const items = response.data.data.items || [];
        
        // 处理返回的数据
        const processedItems = items.map(item => ({
          ...item,
          key: item.id
        }));
        
        setMaterials(processedItems);
        setMaterialsPagination({
          ...materialsPagination,
          current: page,
          pageSize: pageSize,
          total: response.data.data.total || 0
        });
        setMaterialsCurrentPage(page);
        
        // 收集所有的product_id，用于获取产品详情
        const productIds = processedItems
          .map(item => item.product_id)
          .filter(id => id && !productInfoMap[id]);
          
        if (productIds.length > 0) {
          fetchProductDetails(productIds);
        }
      } else {
        message.error('获取BOP物料列表失败: ' + (response.data.message || '未知错误'));
      }
    } catch (error) {
      console.error('获取BOP物料列表错误:', error);
      message.error('获取BOP物料列表失败: ' + (error.message || '网络错误'));
    } finally {
      setMaterialsLoading(false);
    }
  };
  
  // 获取产品详情
  const fetchProductDetails = async (productIds) => {
    if (!productIds || productIds.length === 0) return;
    
    try {
      // 创建一个临时的产品信息映射
      const tempProductInfoMap = { ...productInfoMap };
      
      // 并行获取每个产品的详细信息
      const promises = productIds.map(async (id) => {
        if (tempProductInfoMap[id]) return; // 如果已经有了，就不再获取
        
        try {
          // 使用产品库接口文档中的 GET /api/product_info/{id} 接口
          const response = await axios.get(`${API_BASE_URL}/api/product_info/${id}`);
          if (response.data && response.data.code === 200) {
            tempProductInfoMap[id] = response.data.data;
          }
        } catch (error) {
          console.error(`获取产品 ${id} 详情失败:`, error);
        }
      });
      
      // 等待所有请求完成
      await Promise.all(promises);
      
      // 更新产品信息映射
      setProductInfoMap(tempProductInfoMap);
    } catch (error) {
      console.error('获取产品信息错误:', error);
    }
  };

  // 处理选项卡切换
  const handleTabChange = (tab) => {
    setActiveTab(tab);
    if (tab === 'resources' && resources.length === 0) {
      fetchResourceList(1, resourcesPageSize);
    } else if (tab === 'materials' && materials.length === 0) {
      fetchMaterialList(1, materialsPageSize);
    }
  };

  // 资源列表分页处理
  const handleResourcesPageChange = (page) => {
    setResourcesCurrentPage(page);
    fetchResourceList(page, resourcesPageSize);
  };

  // 资源列表页码输入
  const handleResourcesPageInputChange = (e) => {
    const value = parseInt(e.target.value, 10);
    if (!isNaN(value)) {
      setResourcesCurrentPage(value);
    }
  };

  // 资源列表页码输入框按键事件
  const handleResourcesPageInputKeyPress = (e) => {
    if (e.key === 'Enter') {
      const value = parseInt(e.target.value, 10);
      if (!isNaN(value) && value > 0 && value <= Math.ceil(resourcesPagination.total / resourcesPageSize)) {
        fetchResourceList(value, resourcesPageSize);
      }
    }
  };

  // 资源列表前一页
  const goResourcesPrevPage = () => {
    if (resourcesCurrentPage > 1) {
      const prevPage = resourcesCurrentPage - 1;
      setResourcesCurrentPage(prevPage);
      fetchResourceList(prevPage, resourcesPageSize);
    }
  };

  // 资源列表后一页
  const goResourcesNextPage = () => {
    if (resourcesCurrentPage < Math.ceil(resourcesPagination.total / resourcesPageSize)) {
      const nextPage = resourcesCurrentPage + 1;
      setResourcesCurrentPage(nextPage);
      fetchResourceList(nextPage, resourcesPageSize);
    }
  };

  // 物料列表分页处理
  const handleMaterialsPageChange = (page) => {
    setMaterialsCurrentPage(page);
    fetchMaterialList(page, materialsPageSize);
  };

  // 物料列表页码输入
  const handleMaterialsPageInputChange = (e) => {
    const value = parseInt(e.target.value, 10);
    if (!isNaN(value)) {
      setMaterialsCurrentPage(value);
    }
  };

  // 物料列表页码输入框按键事件
  const handleMaterialsPageInputKeyPress = (e) => {
    if (e.key === 'Enter') {
      const value = parseInt(e.target.value, 10);
      if (!isNaN(value) && value > 0 && value <= Math.ceil(materialsPagination.total / materialsPageSize)) {
        fetchMaterialList(value, materialsPageSize);
      }
    }
  };

  // 物料列表前一页
  const goMaterialsPrevPage = () => {
    if (materialsCurrentPage > 1) {
      const prevPage = materialsCurrentPage - 1;
      setMaterialsCurrentPage(prevPage);
      fetchMaterialList(prevPage, materialsPageSize);
    }
  };

  // 物料列表后一页
  const goMaterialsNextPage = () => {
    if (materialsCurrentPage < Math.ceil(materialsPagination.total / materialsPageSize)) {
      const nextPage = materialsCurrentPage + 1;
      setMaterialsCurrentPage(nextPage);
      fetchMaterialList(nextPage, materialsPageSize);
    }
  };
  
  // 打开产品详情
  const openProductDetail = (productId) => {
    if (!productId) return;
    
    // 获取产品信息
    const productInfo = productInfoMap[productId] || {};
    
    // 打开一个新的页签，用于展示产品详情
    const tabKey = `productDetail-${productId}`;
    const tabTitle = `${productInfo.code || '产品'}`;
    addTab(tabKey, tabTitle, 'ProductDetail', { productId });
  };

  // 格式化日期
  const formatDate = (dateString) => {
    if (!dateString) return '-';
    try {
      const date = new Date(dateString);
      if (!isNaN(date.getTime())) {
        return date.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        }).replace(/\//g, '-');
      }
      return dateString;
    } catch (error) {
      console.error('日期格式化错误:', error);
      return dateString || '-';
    }
  };

  // 状态映射
  const getStatusText = (status) => {
    const statusMap = {
      'active': '生效',
      'inactive': '未生效',
      'draft': '草稿',
      'archived': '归档',
      'published': '发布'
    };
    return statusMap[status] || status || '-';
  };

  // 获取行样式
  const getRowClassName = (data) => {
    if (data.length >= 10 || isMobile) {
      return "table-row-compact-height";
    }
    return "table-row-normal-height";
  };

  // 获取资源列表列定义
  const getResourceColumns = () => {
    return [
      {
        title: '资源编码',
        dataIndex: 'resource_code',
        key: 'resource_code',
        align: 'center',
        ellipsis: true,
        render: (text) => <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{text || '-'}</span>
      },
      {
        title: '资源名称',
        dataIndex: 'resource_name',
        key: 'resource_name',
        align: 'left',
        ellipsis: true,
        render: (text) => <span>{text || '-'}</span>
      },
      {
        title: '资源类型',
        dataIndex: 'resource_type',
        key: 'resource_type',
        align: 'center',
        ellipsis: true,
        render: (text) => <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{text || '-'}</span>
      },
      {
        title: '数量',
        dataIndex: 'quantity',
        key: 'quantity',
        align: 'center',
        ellipsis: true,
        render: (text) => <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{text || '-'}</span>
      },
      {
        title: '单位',
        dataIndex: 'unit',
        key: 'unit',
        align: 'center',
        ellipsis: true,
        render: (text) => <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{text || '-'}</span>
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        key: 'create_time',
        align: 'center',
        ellipsis: true,
        render: (text) => <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{formatDate(text)}</span>
      }
    ];
  };
  
  // 获取物料列表列定义
  const getMaterialColumns = () => {
    return [
      {
        title: '物料编码',
        dataIndex: 'product_id',
        key: 'material_code',
        align: 'center',
        ellipsis: true,
        render: (productId) => {
          const productInfo = productInfoMap[productId] || {};
          return (
            <span 
              style={{ display: 'block', width: '100%', textAlign: 'center', cursor: 'pointer' }}
              onClick={() => openProductDetail(productId)}
            >
              {productInfo.code || '-'}
            </span>
          );
        }
      },
      {
        title: '物料名称',
        dataIndex: 'product_id',
        key: 'material_name',
        align: 'left',
        ellipsis: true,
        render: (productId) => {
          const productInfo = productInfoMap[productId] || {};
          return (
            <span 
              style={{ cursor: 'pointer' }}
              onClick={() => openProductDetail(productId)}
            >
              {productInfo.name || '-'}
            </span>
          );
        }
      },
      {
        title: '物料类型',
        dataIndex: 'product_id',
        key: 'material_type',
        align: 'center',
        ellipsis: true,
        render: (productId) => {
          const productInfo = productInfoMap[productId] || {};
          return <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{productInfo.product_type || '-'}</span>;
        }
      },
      {
        title: '数量',
        dataIndex: 'quantity',
        key: 'quantity',
        align: 'center',
        ellipsis: true,
        render: (text) => <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{text || '-'}</span>
      },
      {
        title: '单位',
        dataIndex: 'unit',
        key: 'unit',
        align: 'center',
        ellipsis: true,
        render: (text) => <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{text || '-'}</span>
      },
      {
        title: '创建时间',
        dataIndex: 'create_time',
        key: 'create_time',
        align: 'center',
        ellipsis: true,
        render: (text) => <span style={{ display: 'block', width: '100%', textAlign: 'center' }}>{formatDate(text)}</span>
      }
    ];
  };

  // 渲染BOP详情内容
  const renderBOPDetail = () => {
    if (!bopDetail) {
      return (
        <div style={{ textAlign: 'center', padding: '30px 0' }}>
          {loading ? '正在加载...' : '暂无数据'}
        </div>
      );
    }
    
    return (
      <div>
        <div className="bop-detail-item">
          <div className="bop-detail-label">编码:</div>
          <div className="bop-detail-value">{bopDetail.code || '-'}</div>
        </div>
        
        <div className="bop-detail-item">
          <div className="bop-detail-label">名称:</div>
          <div className="bop-detail-value">{bopDetail.name || '-'}</div>
        </div>
        
        <div className="bop-detail-item">
          <div className="bop-detail-label">当前版本:</div>
          <div className="bop-detail-value">{bopDetail.current_version || '-'}</div>
        </div>
        
        <div className="bop-detail-item">
          <div className="bop-detail-label">状态:</div>
          <div className="bop-detail-value">{getStatusText(bopDetail.status)}</div>
        </div>
        
        <div className="bop-detail-item">
          <div className="bop-detail-label">创建时间:</div>
          <div className="bop-detail-value">{formatDate(bopDetail.create_time)}</div>
        </div>
        
        <div className="bop-detail-item">
          <div className="bop-detail-label">更新时间:</div>
          <div className="bop-detail-value">{formatDate(bopDetail.update_time)}</div>
        </div>
      </div>
    );
  };
  
  // 渲染资源列表
  const renderResourcesList = () => {
    return (
      <div className="resources-list-container" style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
        <Spin spinning={resourcesLoading}>
          <div style={{ flex: 1, overflow: 'auto' }}>
            <Table
              className={`data-table ${resources.length >= 10 || isMobile ? 'compact-table' : ''}`}
              dataSource={resources}
              columns={getResourceColumns()}
              pagination={false}
              rowClassName={() => resources.length >= 10 || isMobile ? "table-row-compact-height" : "table-row-normal-height"}
              size={isMobile || resources.length >= 10 ? 'small' : 'middle'}
              bordered={true}
              scroll={{ x: isMobile ? 800 : 'max-content' }}
              tableLayout="auto"
              locale={{ emptyText: '暂无数据' }}
            />
          </div>
          
          {/* 自定义分页 */}
          <div className="pagination-container">
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <span>共 {resourcesPagination.total} 条，{Math.ceil(resourcesPagination.total / resourcesPageSize)} 页</span>
            </div>
            
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Button 
                icon={<LeftOutlined />}
                onClick={goResourcesPrevPage}
                disabled={resourcesCurrentPage === 1}
                style={{ marginRight: '8px' }}
              />
              
              <Input
                ref={resourcesInputRef}
                style={{ width: '50px', textAlign: 'center', margin: '0 8px' }}
                value={resourcesCurrentPage}
                onChange={handleResourcesPageInputChange}
                onKeyPress={handleResourcesPageInputKeyPress}
              />
              
              <span style={{ margin: '0 8px' }}>/ {Math.ceil(resourcesPagination.total / resourcesPageSize)}</span>
              
              <Button 
                icon={<RightOutlined />}
                onClick={goResourcesNextPage}
                disabled={resourcesCurrentPage >= Math.ceil(resourcesPagination.total / resourcesPageSize)}
                style={{ marginLeft: '8px', marginRight: '8px' }}
              />
              
              <span style={{ marginLeft: '8px' }}>
                {resourcesPageSize} / 页
              </span>
            </div>
          </div>
        </Spin>
      </div>
    );
  };
  
  // 渲染物料列表
  const renderMaterialsList = () => {
    return (
      <div className="materials-list-container" style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
        <Spin spinning={materialsLoading}>
          <div style={{ flex: 1, overflow: 'auto' }}>
            <Table
              className={`data-table ${materials.length >= 10 || isMobile ? 'compact-table' : ''}`}
              dataSource={materials}
              columns={getMaterialColumns()}
              pagination={false}
              rowClassName={() => materials.length >= 10 || isMobile ? "table-row-compact-height" : "table-row-normal-height"}
              size={isMobile || materials.length >= 10 ? 'small' : 'middle'}
              bordered={true}
              scroll={{ x: isMobile ? 800 : 'max-content' }}
              tableLayout="auto"
              locale={{ emptyText: '暂无数据' }}
            />
          </div>
          
          {/* 自定义分页 */}
          <div className="pagination-container">
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <span>共 {materialsPagination.total} 条，{Math.ceil(materialsPagination.total / materialsPageSize)} 页</span>
            </div>
            
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <Button 
                icon={<LeftOutlined />}
                onClick={goMaterialsPrevPage}
                disabled={materialsCurrentPage === 1}
                style={{ marginRight: '8px' }}
              />
              
              <Input
                ref={materialsInputRef}
                style={{ width: '50px', textAlign: 'center', margin: '0 8px' }}
                value={materialsCurrentPage}
                onChange={handleMaterialsPageInputChange}
                onKeyPress={handleMaterialsPageInputKeyPress}
              />
              
              <span style={{ margin: '0 8px' }}>/ {Math.ceil(materialsPagination.total / materialsPageSize)}</span>
              
              <Button 
                icon={<RightOutlined />}
                onClick={goMaterialsNextPage}
                disabled={materialsCurrentPage >= Math.ceil(materialsPagination.total / materialsPageSize)}
                style={{ marginLeft: '8px', marginRight: '8px' }}
              />
              
              <span style={{ marginLeft: '8px' }}>
                {materialsPageSize} / 页
              </span>
            </div>
          </div>
        </Spin>
      </div>
    );
  };

  return (
    <div className="bop-detail-container">
      <style dangerouslySetInnerHTML={{ __html: customStyles }} />
      
      <div className="bop-detail-header">
        <div className="bop-detail-tabs">
          <div 
            className={`bop-detail-tab ${activeTab === 'detail' ? 'active' : ''}`}
            onClick={() => handleTabChange('detail')}
          >
            BOP详情
          </div>
          <div 
            className={`bop-detail-tab ${activeTab === 'resources' ? 'active' : ''}`}
            onClick={() => handleTabChange('resources')}
          >
            资源列表
          </div>
          <div 
            className={`bop-detail-tab ${activeTab === 'materials' ? 'active' : ''}`}
            onClick={() => handleTabChange('materials')}
          >
            物料列表
          </div>
          <div style={{ flex: 1 }}></div>
          <Button 
            icon={<EditOutlined />} 
            style={{ margin: '8px 0' }}
          >
            编辑
          </Button>
        </div>
      </div>
      
      <Spin spinning={loading && activeTab === 'detail'}>
        <div className="bop-detail-content">
          {activeTab === 'detail' && renderBOPDetail()}
          {activeTab === 'resources' && renderResourcesList()}
          {activeTab === 'materials' && renderMaterialsList()}
        </div>
      </Spin>
    </div>
  );
};

// 导出组件
export { ProductBOP as default, BOPDetail }; 